layui.use(['form', 'layer'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery;


    var region_url = $('.region_url').val();
    var address_url = $('.address_url').val();


    var Region = function () {


        return {
            init: function () {
                if ($('#province').length > 0) {
                    get_province();
                }


                this.onEvent();
            },

            onEvent: function () {

                // 选择省
                /*$('#province').on('change', function () {
                    get_city($(this));

                    $('.province').val($(this).find('option:selected').text());
                    $('.province_id').val($(this).find('option:selected').val());
                    $('.city').val('');
                    $('.city_id').val('');
                    $('.district').val('');
                    $('.district_id').val('');
                });*/
                form.on('select(province)', function (data) {
                    var _this = $('#province');
                    get_city(_this);

                    $('.province').val(_this.find('option:selected').text());
                    //$('.province_id').val(_this.find('option:selected').val());
                    $('.province_id').val(data.value);
                    var province_code = $(data.elem).find('option:selected').attr('data-code');
                    $('.city').val('');
                    $('.city_id').val('');
                    $('.district').val('');
                    $('.district_id').val('');
                });

                // 选择城市
                /*$('#city').on('change', function () {
                    if ($('#district').length > 0) {
                        get_district($(this));
                    }

                    $('.city').val($(this).find('option:selected').text());
                    $('.city_id').val($(this).find('option:selected').val());
                    $('.district').val('');
                    $('.district_id').val('');
                });*/
                form.on('select(city)', function (data) {
                    var _this = $('#city');
                    get_district(_this);

                    $('.city').val(_this.find('option:selected').text());
                    $('.city_id').val(_this.find('option:selected').val());
                    $('.district').val('');
                    $('.district_id').val('');
                });

                // 选择区
                /*$('#district').on('change', function () {
                    $('.district').val($(this).find('option:selected').text());
                    $('.district_id').val($(this).find('option:selected').val());
                });*/
                form.on('select(district)', function (data) {
                    var _this = $('#district');

                    $('.district').val(_this.find('option:selected').text());
                    $('.district_id').val(_this.find('option:selected').val());
                });
            }
        };

    }();


    /**
     * 获取省
     */
    function get_province() {
        $('#city').html('<option value="0">选择市</option>');
        $('#district').html('<option value="0">选择区</option>');
        //$('#town').html('<option value="0">请选择乡镇</option>');

        var url = region_url + '?level=1&p_id=0';
        $.ajax({
            type: "GET",
            url: url,
            data: {},
            //dataType:"json",
            error: function (request) {
                layer.msg("服务器繁忙, 请联系管理员!");
                return false;
            },
            success: function (data) {
                var options = '<option value="0">选择省</option>' + data;
                $('#province').empty().html(options);

                if ($('#province').data('field') == 'id') {
                    var province_id = $('.province_id').val();
                    if (province_id) {
                        $('#province').val(province_id);
                        get_city($('#province'));
                    }
                } else {
                    var province = $('.province').val();
                    if (province) {
                        /*$("#province option").filter(function () {
                            return $(this).text() == province;
                        }).prop('selected', true);*/
                        //$("#province").find("option[text='" + province_name + "']").attr('selected', true);
                        $('#province').find("option:contains('" + province + "')").attr('selected', true);
                        get_city($('#province'));
                    }
                }

                form.render();
            }
        });
        return false;
    }

    /**
     * 获取城市
     * @param select对象
     */
    function get_city(obj) {
        var parent_id = $(obj).val();
        if (!parent_id > 0) {
            return false;
        }
        $('#district').html('<option value="0">选择区</option>');

        var url = region_url + '?level=2&p_id=' + parent_id;
        $.ajax({
            type: "GET",
            url: url,
            data: {},
            //dataType:"json",
            error: function (request) {
                layer.msg("服务器繁忙, 请联系管理员!");
                return false;
            },
            success: function (data) {
                var options = '<option value="0">选择市</option>' + data;
                $('#city').empty().html(options);

                if ($('#city').data('field') == 'id') {
                    var city_id = $('.city_id').val();
                    if (city_id) {
                        $('#city').val(city_id);
                        if ($('#district').length > 0) {
                            get_district($('#city'));
                        }
                    }
                } else {
                    var city = $('.city').val();
                    if (city) {
                        $('#city').find("option:contains('" + city + "')").attr('selected', true);
                        if ($('#district').length > 0) {
                            get_district($('#city'));
                        }
                    }
                }

                form.render();
            }
        });
        return false;
    }

    /**
     * 获取区
     * @param select对象
     */
    function get_district(obj) {
        var parent_id = $(obj).val();
        if (!parent_id > 0) {
            return;
        }

        var url = region_url + '?level=3&p_id=' + parent_id;
        $.ajax({
            type: "GET",
            url: url,
            data: {},
            //dataType:"json",
            error: function (request) {
                layer.msg("服务器繁忙, 请联系管理员!");
                return false;
            },
            success: function (data) {
                var options = '<option value="0">选择区</option>' + data;
                $('#district').empty().html(options);

                if ($('#district').data('field') == 'id') {
                    var district_id = $('.district_id').val();
                    if (district_id) {
                        $('#district').val(district_id);
                    }
                } else {
                    var district = $('.district').val();
                    if (district) {
                        $('#district').find("option:contains('" + district + "')").attr('selected', true);
                    }
                }

                form.render();
            }
        });
        return false;
    }

    /**
     * 获取最后一级乡镇
     * @param obj
     */
    function get_town(obj) {
        var parent_id = $(obj).val();
        if (!parent_id > 0) {
            return;
        }

        var url = region_url + '?level=4&p_id=' + parent_id;
        $.ajax({
            type: "GET",
            url: url,
            data: {},
            //dataType:"json",
            error: function (request) {
                layer.msg("服务器繁忙, 请联系管理员!");
                return false;
            },
            success: function (data) {
                var options = '<option value="0">选择乡镇</option>' + data;
                $('#town').empty().html(options);

                if ($('#town').data('field') == 'id') {
                    var town_id = $('.town_id').val();
                    if (town_id) {
                        $('#town').val(town_id);
                    }
                } else {
                    var town = $('.town').val();
                    if (town) {
                        $('#town').find("option:contains('" + town + "')").attr('selected', true);
                    }
                }

                form.render();
            }
        });
        return false;
    }

    /**
     * ajax获取详细地址
     */
    function ajax_address(address_id) {
        var url = address_url;
        $.ajax({
            type: "POST",
            url: url,
            data: 'address_id=' + address_id,
            dataType: "json",
            success: function (data) {
                var province_html = '';
                for (var i = 0; i < data.province.length; i++) {
                    var province = data.province[i];
                    province_html += '<option value="' + province['id'] + '">' + province['name'] + '</option>';
                }
                var city_html = '';
                for (var i = 0; i < data.city.length; i++) {
                    var city = data.city[i];
                    city_html += '<option value="' + city['id'] + '">' + city['name'] + '</option>';
                }
                var district_html = '';
                for (var i = 0; i < data.district.length; i++) {
                    var district = data.district[i];
                    district_html += '<option value="' + district['id'] + '">' + district['name'] + '</option>';
                }
                var town_html = '';
                for (var i = 0; i < data.town.length; i++) {
                    var town = data.town[i];
                    town_html += '<option value="' + town['id'] + '">' + town['name'] + '</option>';
                }

                $('#province').html(province_html);
                $('#city').html(city_html);
                $('#district').html(district_html);
                $('#town').html(town_html);
            }
        });
        return false;
    }


    // 以下是方法二（不推荐）
    /**
     * 根据ID查询下一级的市县
     */
    $('.city').on('click', function () {
        var parent_id = $(this).val();
        var _this = $(this);
        var url = region_url;
        $.ajax({
            type: "POST",
            url: url,
            data: 'p_id=' + parent_id,
            dataType: "json",
            success: function (res) {
                if (res) {
                    var options = '<option value="0">请选择</option>';
                    for (var i = 0; i < res.length; i++) {
                        var data = res[i];
                        options += '<option value="' + data['id'] + '">' + data['name'] + '</option>';
                    }
                    _this.nextAll().html('<option value="0">请选择上一级</option>');
                    _this.next().html(options);
                }
            }
        });
        return false;
    });

    $(function () {
        Region.init();
    });
});